<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.example.dao.CartDao" %>
<%@ page import="com.example.dao.ProductDao" %>
<%@ page import="com.example.domain.CartWithProduct" %>
<%@ page import="com.example.domain.Product" %>
<%@ page import="com.example.domain.User" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Optional" %>
<html>
<head>
    <title>购物车 - 购物网</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <style>
        /* 页面头部 */
        .page-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, #6c89ff 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
            box-shadow: var(--shadow-md);
        }
        
        .page-title {
            text-align: center;
            margin: 0;
            font-size: 2.5rem;
            font-weight: 600;
            text-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        
        .page-subtitle {
            text-align: center;
            margin-top: 0.5rem;
            font-size: 1.1rem;
            opacity: 0.9;
        }
        
        .breadcrumb {
            display: flex;
            justify-content: center;
            margin-top: 1rem;
            font-size: 0.9rem;
        }
        
        .breadcrumb a {
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: var(--transition);
        }
        
        .breadcrumb a:hover {
            color: white;
            text-decoration: underline;
        }
        
        .breadcrumb span {
            margin: 0 0.5rem;
            opacity: 0.8;
        }
        
        /* 空购物车样式 */
        .empty-cart {
            text-align: center;
            padding: 3rem;
            background: var(--white-color);
            border-radius: var(--border-radius-lg);
            box-shadow: var(--shadow);
            transition: var(--transition);
        }
        
        .empty-cart:hover {
            box-shadow: var(--shadow-md);
        }
        
        .empty-cart-icon {
            font-size: 6rem;
            margin-bottom: 1rem;
            color: var(--gray-300);
            transition: var(--transition);
        }
        
        .empty-cart:hover .empty-cart-icon {
            color: var(--primary-color);
            transform: scale(1.05);
        }
        
        /* 购物车摘要 */
        .cart-summary {
            background-color: var(--white-color);
            border-radius: var(--border-radius-lg);
            padding: 1.5rem;
            margin-top: 1.5rem;
            box-shadow: var(--shadow);
            border: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            transition: var(--transition);
        }
        
        .cart-summary:hover {
            box-shadow: var(--shadow-md);
        }
        
        .cart-summary-actions {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        /* 商品图片 */
        .product-image-small {
            width: 80px;
            height: 80px;
            object-fit: contain;
            border-radius: var(--border-radius);
            background-color: var(--gray-50);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;
            border: 1px solid var(--gray-200);
            transition: var(--transition);
        }
        
        .product-image-small:hover {
            transform: scale(1.05);
            box-shadow: var(--shadow);
        }
        
        .no-image-text {
            color: var(--gray-500);
            font-size: 0.8rem;
        }
        
        /* 加载指示器 */
        .loading-spinner {
            display: none;
            width: 20px;
            height: 20px;
            border: 2px solid var(--gray-200);
            border-top: 2px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 通知消息 */
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 1rem 1.5rem;
            border-radius: var(--border-radius);
            color: white;
            font-weight: 500;
            z-index: 1000;
            display: none;
            box-shadow: var(--shadow-lg);
            animation: slideInRight 0.3s ease-out;
        }
        
        .notification.success {
            background-color: var(--success-color);
        }
        
        .notification.error {
            background-color: var(--danger-color);
        }
        
        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        /* 商品列表样式 */
        .cart-item-list {
            width: 100%;
        }
        
        .cart-item {
            display: flex;
            padding: 1.5rem;
            border-bottom: 1px solid var(--border-color);
            align-items: center;
            transition: all 0.3s ease;
            background: var(--white-color);
        }
        
        .cart-item:hover {
            background-color: var(--gray-50);
            transform: translateX(5px);
        }
        
        .cart-item:last-child {
            border-bottom: none;
        }
        
        .cart-item-select {
            width: 5%;
            display: flex;
            align-items: center;
        }
        
        .cart-item-info {
            width: 40%;
            display: flex;
            align-items: center;
        }
        
        .cart-item-info div:last-child {
            font-weight: 500;
            color: var(--gray-800);
        }
        
        .cart-item-price-col {
            width: 15%;
            font-weight: bold;
            color: var(--gray-700);
        }
        
        .cart-item-quantity-col {
            width: 15%;
        }
        
        .cart-item-total-col {
            width: 15%;
            font-weight: bold;
            color: var(--primary-color);
            font-size: 1.1rem;
        }
        
        .cart-item-action-col {
            width: 10%;
        }
        
        /* 数量控制样式 */
        .quantity-control {
            display: flex;
            align-items: center;
            border: 1px solid var(--gray-300);
            border-radius: var(--border-radius);
            width: 120px;
            overflow: hidden;
            box-shadow: var(--shadow-sm);
            background: var(--white-color);
            transition: var(--transition);
        }
        
        .quantity-control:focus-within {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(66, 99, 235, 0.1);
        }
        
        .quantity-btn {
            width: 36px;
            height: 36px;
            background-color: var(--gray-50);
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            font-weight: bold;
            color: var(--gray-700);
            transition: var(--transition);
            position: relative;
        }
        
        .quantity-btn:hover {
            background-color: var(--primary-color);
            color: white;
        }
        
        .quantity-btn:active {
            transform: scale(0.95);
        }
        
        .quantity-input {
            flex: 1;
            height: 36px;
            border: none;
            text-align: center;
            font-size: 1rem;
            background: var(--white-color);
            outline: none;
        }
        
        /* 删除按钮 */
        .delete-btn {
            color: var(--gray-500);
            background: none;
            border: none;
            cursor: pointer;
            padding: 0.5rem;
            border-radius: var(--border-radius);
            transition: var(--transition);
            font-size: 1rem;
        }
        
        .delete-btn:hover {
            background-color: var(--danger-color);
            color: white;
            transform: scale(1.1);
        }
        
        /* 选择控件 */
        .select-all-container {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 1rem 1.5rem;
            background-color: var(--gray-50);
            font-weight: 500;
            border-radius: var(--border-radius-lg) var(--border-radius-lg) 0 0;
            border-bottom: 1px solid var(--border-color);
        }
        
        /* 自定义复选框 */
        input[type="checkbox"] {
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            width: 20px;
            height: 20px;
            background-color: var(--white-color);
            border: 2px solid var(--gray-300);
            border-radius: var(--border-radius);
            cursor: pointer;
            position: relative;
            transition: var(--transition);
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        input[type="checkbox"]:hover {
            border-color: var(--primary-color);
        }
        
        input[type="checkbox"]:checked {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        input[type="checkbox"]:checked::after {
            content: "✓";
            color: white;
            font-size: 14px;
            font-weight: bold;
        }
        
        /* 文本信息 */
        .selected-info {
            font-weight: 500;
            color: var(--gray-600);
        }
        
        .total-price {
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--primary-color);
        }
        
        /* 结算按钮 */
        .checkout-btn {
            padding: 0.875rem 2rem;
            font-size: 1rem;
            font-weight: 600;
            transition: var(--transition);
            border-radius: var(--border-radius);
            position: relative;
            overflow: hidden;
            z-index: 1;
        }
        
        .checkout-btn::before {
            content: "";
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
            transition: 0.5s;
            z-index: -1;
        }
        
        .checkout-btn:hover::before {
            left: 100%;
        }
        
        /* 表头 */
        .header-row {
            display: flex;
            padding: 1rem 1.5rem;
            background-color: var(--gray-50);
            font-weight: 600;
            border-bottom: 1px solid var(--border-color);
            color: var(--gray-700);
        }
        
        /* 卡片样式 */
        .card {
            background: var(--white-color);
            border-radius: var(--border-radius-lg);
            box-shadow: var(--shadow);
            overflow: hidden;
            transition: var(--transition);
        }
        
        .card:hover {
            box-shadow: var(--shadow-md);
        }
        
        /* 响应式设计 */
        @media (max-width: 1024px) {
            .page-title {
                font-size: 2rem;
            }
            
            .cart-item-info {
                width: 35%;
            }
            
            .cart-item-price-col,
            .cart-item-quantity-col,
            .cart-item-total-col {
                width: 15%;
            }
            
            .cart-item-action-col {
                width: 10%;
            }
        }
        
        @media (max-width: 768px) {
            .cart-item {
                flex-wrap: wrap;
                padding: 1rem;
                gap: 0.5rem;
            }
            
            .cart-item-select,
            .cart-item-action-col {
                width: 15%;
            }
            
            .cart-item-price-col,
            .cart-item-quantity-col,
            .cart-item-total-col {
                width: 26.66%;
                font-size: 0.9rem;
            }
            
            .cart-item-info {
                width: 100%;
                margin-bottom: 1rem;
                border-bottom: 1px dashed var(--border-color);
                padding-bottom: 0.5rem;
            }
            
            .cart-summary {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
            
            .cart-summary-actions {
                flex-direction: column;
                width: 100%;
                gap: 0.5rem;
            }
            
            .page-title {
                font-size: 1.75rem;
            }
            
            .page-subtitle {
                font-size: 1rem;
            }
            
            .header-row {
                display: none;
            }
            
            .quantity-control {
                width: 100%;
            }
            
            .product-image-small {
                width: 60px;
                height: 60px;
            }
        }
        
        @media (max-width: 480px) {
            .empty-cart-icon {
                font-size: 4rem;
            }
            
            .cart-item-price-col,
            .cart-item-quantity-col,
            .cart-item-total-col {
                width: 30%;
            }
            
            .cart-item-select,
            .cart-item-action-col {
                width: 10%;
            }
        }
    </style>
</head>
<body>
    <% 
        // 检查用户是否已登录
        com.example.domain.User currentUser = (com.example.domain.User) session.getAttribute("user");
    %>
    
    <!-- 导航栏 -->
    <nav class="header-nav">
        <div class="nav-container">
            <a href="../index.jsp" class="nav-brand">
                🛒 购物网
            </a>
            
            <!-- 搜索框 -->
            <div style="flex: 1; max-width: 400px; margin: 0 20px; position: relative;">
                <input type="text" placeholder="搜索商品..." style="width: 100%; padding: 10px 15px; padding-right: 40px; border-radius: var(--border-radius); border: 1px solid var(--gray-300); transition: var(--transition);">
                <button style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; color: var(--gray-500); cursor: pointer; font-size: 1.2rem;">
                    🔍
                </button>
            </div>
            
            <ul class="nav-links">
                <li><a href="../index.jsp">首页</a></li>
                <li><a href="../products/list.jsp">商品浏览</a></li>
                <li><a href="cart.jsp" class="active">购物车</a></li>
                <% if (currentUser != null) { %>
                    <li><a href="../admin/user_info.jsp">用户中心</a></li>
                <% } %>
            </ul>
            
            <div class="user-actions">
                <% if (currentUser != null) { %>
                    <span class="user-info">欢迎, <%= currentUser.getUsername() %>!</span>
                    <a href="../auth/logout.jsp" class="btn btn-outline">退出</a>
                <% } else { %>
                    <a href="../auth/login.jsp" class="btn btn-outline">登录</a>
                    <a href="../auth/register.jsp" class="btn" style="margin-left: 10px;">注册</a>
                <% } %>
            </div>
        </div>
    </nav>
    
    <!-- 页面头部 -->
    <div class="page-header">
        <div class="container">
            <h1 class="page-title">我的购物车</h1>
            <p class="page-subtitle">查看和管理您已添加的商品</p>
            <div class="breadcrumb">
                <a href="../index.jsp">首页</a>
                <span>/</span>
                <span>购物车</span>
            </div>
        </div>
    </div>
    
    <!-- 通知消息 -->
    <div id="notification" class="notification"></div>
    
    <div class="container">
        <% if (currentUser == null) { %>
            <div class="empty-cart">
                <div class="empty-cart-icon">🛒</div>
                <h3>请先登录</h3>
                <p style="margin: 1rem 0; color: var(--gray-600);">您需要登录后才能查看和管理购物车</p>
                <a href="../auth/login.jsp" class="btn">立即登录</a>
            </div>
        <% } else { %>
            <% try { %>
                <% 
                    CartDao cartDao = new CartDao();
                    ProductDao productDao = new ProductDao();
                    List<CartWithProduct> cartItems = cartDao.getCartListByMemberId(currentUser.getId());
                    double totalPrice = 0;
                    
                    // 计算购物车总价
                    for (CartWithProduct item : cartItems) {
                        totalPrice += item.getSale_money();
                    }
                    
                    if (cartItems.isEmpty()) {
                %>
                    <div class="empty-cart">
                        <div class="empty-cart-icon">🛒</div>
                        <h3>购物车为空</h3>
                        <p style="margin: 1rem 0; color: var(--gray-600);">您还没有添加任何商品到购物车</p>
                        <a href="../products/list.jsp" class="btn">去购物</a>
                    </div>
                <% } else { %>
                <div class="card">
                    <div class="select-all-container">
                        <input type="checkbox" id="selectAll">
                        <label for="selectAll" style="cursor: pointer; color: var(--gray-700);">全选</label>
                    </div>
                    
                    <div class="header-row">
                        <div style="width: 5%;"></div>
                        <div style="width: 40%;">商品信息</div>
                        <div style="width: 15%;">单价</div>
                        <div style="width: 15%;">数量</div>
                        <div style="width: 15%;">小计</div>
                        <div style="width: 10%;">操作</div>
                    </div>
                    
                    <div class="cart-item-list">
                <% 
                            for (CartWithProduct item : cartItems) {
                                // 获取商品详细信息以获取图片
                                Optional<Product> productOpt = productDao.getProductById(item.getProduct_id());
                                Product product = productOpt.orElse(null);
                                
                                double itemTotal = item.getSale_money();
                        %>
                        <div class="cart-item fade-in" data-product-id="<%= item.getProduct_id() %>">
                            <div class="cart-item-select">
                                <input type="checkbox" name="selectedItems" value="<%= item.getProduct_id() %>" data-price="<%= itemTotal %>">
                            </div>
                            <div class="cart-item-info">
                                <% if (product != null && product.getLogo() != null && !product.getLogo().isEmpty()) { %>
                                    <img src="<%= request.getContextPath() + "/" + product.getLogo() %>" alt="<%= item.getProduct_name() %>" class="product-image-small">
                                <% } else { %>
                                    <div class="product-image-small">
                                        <span class="no-image-text">暂无图片</span>
                                    </div>
                                <% } %>
                                <div>
                                    <div style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"><%= item.getProduct_name() %></div>
                                </div>
                            </div>
                            <div class="cart-item-price-col">¥<%= String.format("%.2f", item.getSale_price()) %></div>
                            <div class="cart-item-quantity-col">
                                <div class="quantity-control">
                                    <button class="quantity-btn" onclick="updateQuantity(<%= item.getProduct_id() %>, -1)">-</button>
                                    <input type="text" class="quantity-input" value="<%= item.getSale_num() %>" readonly>
                                    <button class="quantity-btn" onclick="updateQuantity(<%= item.getProduct_id() %>, 1)">+</button>
                                </div>
                            </div>
                            <div class="cart-item-total-col">¥<%= String.format("%.2f", itemTotal) %></div>
                            <div class="cart-item-action-col">
                                <button class="delete-btn" onclick="removeFromCart(<%= item.getProduct_id() %>)">🗑️</button>
                            </div>
                        </div>
                        <% 
                            }
                        %>
                    </div>
                </div>
                
                <div class="cart-summary">
                    <div>
                        <input type="checkbox" id="selectAllBottom">
                        <label for="selectAllBottom" style="cursor: pointer; color: var(--gray-700); margin-left: 0.5rem;">全选</label>
                        <span class="selected-info" style="margin-left: 1rem;">
                            已选择 <span id="selected-count">0</span> 件商品
                        </span>
                    </div>
                    <div class="cart-summary-actions">
                        <span style="font-size: 1.1rem; font-weight: 500; color: var(--gray-700);">总计：</span>
                        <span class="total-price">¥<%= String.format("%.2f", totalPrice) %></span>
                        <button class="btn btn-success checkout-btn" onclick="checkout()" id="checkout-btn">去结算</button>
                    </div>
                </div>
                <% } %>
            <% } catch (Exception e) { %>
                <div class="card" style="padding: 2rem; text-align: center; color: var(--danger-color);">
                    <p>加载购物车数据失败: <%= e.getMessage() %></p>
                </div>
            <% } %>
        <% } %>
    </div>
    
    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="footer-top">
                <div>
                    <a href="../index.jsp" class="footer-logo">🛒 购物网</a>
                    <p style="margin-top: 1rem; color: var(--gray-400); font-size: 0.9rem;">
                        优质商品，优质服务，打造您的理想购物体验。
                    </p>
                </div>
                
                <div>
                    <h4 class="footer-heading">快速链接</h4>
                    <ul class="footer-links">
                        <li><a href="../index.jsp">首页</a></li>
                        <li><a href="../products/list.jsp">商品浏览</a></li>
                        <li><a href="#">关于我们</a></li>
                        <li><a href="#">联系我们</a></li>
                    </ul>
                </div>
                
                <div>
                    <h4 class="footer-heading">客户服务</h4>
                    <ul class="footer-links">
                        <li><a href="#">帮助中心</a></li>
                        <li><a href="#">售后政策</a></li>
                        <li><a href="#">配送信息</a></li>
                        <li><a href="#">常见问题</a></li>
                    </ul>
                </div>
            </div>
            
            <div class="footer-bottom">
                <p>&copy; 2025 购物网. 保留所有权利.</p>
            </div>
        </div>
    </footer>
    
    <!-- 加载指示器 -->
    <div id="loading-spinner" class="loading-spinner"></div>
    
    <script>
        // 显示通知消息
        function showNotification(message, isSuccess) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = 'notification ' + (isSuccess ? 'success' : 'error');
            notification.style.display = 'block';
            
            setTimeout(() => {
                notification.style.animation = 'slideInRight 0.3s ease-in reverse';
                setTimeout(() => {
                    notification.style.display = 'none';
                }, 300);
            }, 3000);
        }
        
        // 更新商品数量
        function updateQuantity(productId, change) {
            var item = document.querySelector('.cart-item[data-product-id="' + productId + '"]');
            var container = event.target.closest('.quantity-control');
            var input = container.querySelector('.quantity-input');
            var priceElement = item.querySelector('.cart-item-price-col');
            var subtotalElement = item.querySelector('.cart-item-total-col');
            
            var currentValue = parseInt(input.value);
            var newValue = currentValue + change;
            
            // 显示加载指示器
            document.getElementById('loading-spinner').style.display = 'block';
            
            // 发送 AJAX 请求更新购物车
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '../api/update.jsp', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    document.getElementById('loading-spinner').style.display = 'none';
                    if (xhr.status === 200) {
                        try {
                            var result = JSON.parse(xhr.responseText);
                            if (result.success) {
                                // 如果商品被删除
                                if (result.removed) {
                                    // 找到对应的行并移除（带动画效果）
                                    var item = document.querySelector('.cart-item[data-product-id="' + productId + '"]');
                                    if (item) {
                                        item.style.opacity = '0';
                                        item.style.height = '0';
                                        item.style.margin = '0';
                                        item.style.padding = '0';
                                        item.style.overflow = 'hidden';
                                        item.style.transition = 'all 0.3s ease';
                                        setTimeout(() => {
                                            item.remove();
                                        }, 300);
                                    }
                                    
                                    // 重新计算总价
                                    updateCartTotal();
                                    
                                    showNotification(result.message, true);
                                    
                                    // 如果购物车为空，刷新页面显示空购物车提示
                                    var items = document.querySelectorAll('.cart-item');
                                    if (items.length === 0) {
                                        location.reload();
                                    }
                                } else {
                                    // 更新成功，局部更新页面内容
                                    // 添加数字变化动画
                                    const animateNumberChange = (start, end) => {
                                        const duration = 300;
                                        const startTime = performance.now();
                                        
                                        function updateNumber(currentTime) {
                                            const elapsed = currentTime - startTime;
                                            const progress = Math.min(elapsed / duration, 1);
                                            const current = Math.round(start + (end - start) * progress);
                                            input.value = current;
                                            
                                            if (progress < 1) {
                                                requestAnimationFrame(updateNumber);
                                            }
                                        }
                                        
                                        requestAnimationFrame(updateNumber);
                                    };
                                    
                                    animateNumberChange(currentValue, result.quantity);
                                    
                                    // 更新小计
                                    var subtotal = result.quantity * result.unitPrice;
                                    subtotalElement.textContent = '¥' + subtotal.toFixed(2);
                                    
                                    // 更新对应复选框的data-price属性
                                    var checkbox = item.querySelector('input[name="selectedItems"]');
                                    checkbox.setAttribute('data-price', subtotal);
                                    
                                    // 重新计算总价
                                    updateCartTotal();
                                    
                                    showNotification(result.message, true);
                                }
                            } else {
                                showNotification('更新失败: ' + result.message, false);
                                
                                // 如果是数量不能小于1的错误，并且当前值为1，则重置为1
                                if (newValue < 1 && currentValue == 1) {
                                    input.value = 1;
                                }
                            }
                        } catch (e) {
                            showNotification('解析响应失败: ' + e.message, false);
                        }
                    } else {
                        showNotification('网络错误: ' + xhr.status, false);
                    }
                }
            };
            xhr.send('productId=' + productId + '&quantity=' + newValue);
        }
        
        // 更新购物车总价
        function updateCartTotal() {
            var selectedCheckboxes = document.querySelectorAll('input[name="selectedItems"]:checked');
            var total = 0;
            var count = 0;
            
            // 只计算选中商品的小计总和
            for (var i = 0; i < selectedCheckboxes.length; i++) {
                var price = parseFloat(selectedCheckboxes[i].getAttribute('data-price')) || 0;
                total += price;
                
                // 获取商品数量
                var item = selectedCheckboxes[i].closest('.cart-item');
                var quantityInput = item.querySelector('.quantity-input');
                var quantity = parseInt(quantityInput.value) || 0;
                count += quantity;
            }
            
            var totalPriceElement = document.querySelector('.total-price');
            if (totalPriceElement) {
                // 添加价格变化动画效果
                const previousTotal = parseFloat(totalPriceElement.textContent.replace('¥', ''));
                if (previousTotal !== total) {
                    totalPriceElement.style.transition = 'color 0.3s ease';
                    totalPriceElement.style.color = '#ff6b35';
                    setTimeout(() => {
                        // 修复：获取CSS变量值而不是直接使用
                        const root = document.documentElement;
                        const primaryColor = getComputedStyle(root).getPropertyValue('--primary-color').trim();
                        totalPriceElement.style.color = primaryColor || '#ff6b35';
                    }, 300);
                }
                totalPriceElement.textContent = '¥' + total.toFixed(2);
            }
            
            // 更新选中商品数量
            document.getElementById('selected-count').textContent = count;
        }
        
        // 从购物车中移除商品
        function removeFromCart(productId) {
            if (confirm('确定要从购物车中删除这个商品吗？')) {
                // 显示加载指示器
                document.getElementById('loading-spinner').style.display = 'block';
                
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '../api/remove.jsp', true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        document.getElementById('loading-spinner').style.display = 'none';
                        if (xhr.status === 200) {
                            if (xhr.responseText === 'success') {
                                // 找到对应的行并移除（带动画效果）
                                var item = document.querySelector('.cart-item[data-product-id="' + productId + '"]');
                                if (item) {
                                    item.style.opacity = '0';
                                    item.style.height = '0';
                                    item.style.margin = '0';
                                    item.style.padding = '0';
                                    item.style.overflow = 'hidden';
                                    item.style.transition = 'all 0.3s ease';
                                    setTimeout(() => {
                                        item.remove();
                                    }, 300);
                                }
                                
                                // 重新计算总价
                                updateCartTotal();
                                
                                showNotification('删除成功', true);
                                
                                // 如果购物车为空，刷新页面显示空购物车提示
                                var items = document.querySelectorAll('.cart-item');
                                if (items.length === 0) {
                                    location.reload();
                                }
                            } else {
                                showNotification('删除失败: ' + xhr.responseText, false);
                            }
                        } else {
                            showNotification('网络错误: ' + xhr.status, false);
                        }
                    }
                };
                xhr.send('productId=' + productId);
            }
        }
        
        // 结算
        function checkout() {
            // 获取所有选中的复选框
            var selectedItems = document.querySelectorAll('input[name="selectedItems"]:checked');
            
            if (selectedItems.length === 0) {
                showNotification('请选择至少一件商品', false);
                return;
            }
            
            // 禁用结算按钮防止重复点击
            var checkoutBtn = document.getElementById('checkout-btn');
            checkoutBtn.disabled = true;
            checkoutBtn.textContent = '处理中...';
            checkoutBtn.classList.add('loading');
            
            // 构建表单数据
            var form = document.createElement('form');
            form.method = 'POST';
            form.action = '../order/process.jsp';
            
            // 添加选中的商品ID到表单中
            selectedItems.forEach(function(item) {
                var input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'selectedItems';
                input.value = item.value;
                form.appendChild(input);
            });
            
            document.body.appendChild(form);
            form.submit();
        }
        
        // 全选功能
        document.getElementById('selectAll').addEventListener('change', function() {
            var checkboxes = document.getElementsByName('selectedItems');
            for (var i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = this.checked;
            }
            document.getElementById('selectAllBottom').checked = this.checked;
            // 当全选状态改变时更新总价
            updateCartTotal();
        });
        
        document.getElementById('selectAllBottom').addEventListener('change', function() {
            var checkboxes = document.getElementsByName('selectedItems');
            for (var i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = this.checked;
            }
            document.getElementById('selectAll').checked = this.checked;
            // 当全选状态改变时更新总价
            updateCartTotal();
        });
        
        // 监听每个复选框的变化
        window.addEventListener('load', function() {
            var itemCheckboxes = document.querySelectorAll('input[name="selectedItems"]');
            itemCheckboxes.forEach(function(checkbox) {
                checkbox.addEventListener('change', updateCartTotal);
            });
            
            // 初始化总价计算
            updateCartTotal();
        });
    </script>
</body>
</html>